package com.ant.storage.service.impl;


import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.ant.storage.mapper.MenuMapper;
import com.ant.storage.pojo.Menu;
import com.ant.storage.service.IMenuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Override
    public  List<Menu> menuList() {
        List<Menu> list = baseMapper.selectList(new QueryWrapper<Menu>().orderByAsc("order_num"));
        //        获取根节点
        List<Menu> menuList = list.stream()
                .filter(e -> e.getParentId()==0)
                .map(e -> {
                    e.setChildren(getChildrens(e, list));
                    return e;
                }).collect(Collectors.toList());
        return menuList;
    }


    @Override
    public List<Tree<String>> menuTreeList() {
        List<Menu> menusList = baseMapper.selectList(null);
                TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
                // 最大递归深度
                treeNodeConfig.setDeep(3);
                List<Tree<String>> treeNodes = TreeUtil.build(menusList, "0", treeNodeConfig,
                        (treeNode, tree) -> {
                            //这俩属性必须设置
                            tree.setId(treeNode.getId().toString());
                            tree.setParentId(treeNode.getParentId().toString());
        //                    // 扩展属性 ...
                            tree.putExtra("title", treeNode.getTitle());
                            tree.putExtra("name", treeNode.getName());
                            tree.putExtra("orderNum", treeNode.getOrderNum());
                            tree.putExtra("path", treeNode.getOrderNum());
                            tree.putExtra("component", treeNode.getOrderNum());
                            tree.putExtra("menuType", treeNode.getMenuType());
                            tree.putExtra("visible", treeNode.getVisible());
                            tree.putExtra("perms", treeNode.getPerms());
                        });
        return treeNodes;
    }

    // 递归获取子节点
    private List<Menu> getChildrens(Menu menu, List<Menu> list) {
        List<Menu> children = list.stream()
                .filter(m -> Objects.equals(menu.getId(), m.getParentId()))
                .map(m -> {
                    m.setChildren(getChildrens(m, list));
                    return m;
                }).collect(Collectors.toList());
        return children;
    }
}
